package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.Export;
import cn.itcast.domain.cargo.Packing;
import cn.itcast.domain.cargo.Shipping;
import cn.itcast.domain.cargo.ShippingExample;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.service.cargo.PackingService;
import cn.itcast.service.cargo.ShippingService;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/shipping")
@Slf4j
public class EntrustController extends BaseController {

    @Reference
    private ShippingService shippingService;
    @Reference
    private PackingService packingService;
    @Reference
    private ExportService exportService;


    /**
     *分页列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize){
        log.info("委托分页列表");
        //封装查找参数
        ShippingExample example = new ShippingExample();
        example.createCriteria().andCompanyIdEqualTo(getLoginCompanyId());
        //根据封装的参数找委托分页列表
        PageInfo<Shipping> pageInfo = shippingService.findAll(example, pageNum, pageSize);
        //保存
        request.setAttribute("pageInfo",pageInfo);
        return "cargo/entrust/entrust-list";
    }

    /**
     *跳转到生成委托单页面
     * @param id
     * @return cargo/entrust/entrust-add
     */
    @RequestMapping("/toAdd")
    public String toAdd(String id){
        log.info("跳转至添加页面");
        //根据id查找装箱单
        Packing byId = packingService.findById(id);
        //分割报运单数组ExportIds
        String[] split = byId.getExportIds().split(",");
        //根据报运单id查找报运单
        Export byId1 = exportService.findById(split[0]);
        //创建一个委托单对象
        Shipping shipping = new Shipping();
        //设置信用证号
        shipping.setLcNo(byId1.getLcno());
        //设置装运港
        shipping.setPortOfLoading(byId1.getShipmentPort());
        //设置卸货港
        shipping.setPortOfDischar(byId1.getDestinationPort());
        //设置货主
        shipping.setShipper("传智播客");
        //保存
        request.setAttribute("id",id);
        request.setAttribute("entrust",shipping);
        return "cargo/entrust/entrust-add";
    }
    /**生成委托单
     * cargo/shipping/edit.do
     * @param shipping
     * @return redirect:/cargo/shipping/list.do
     */
    @RequestMapping("/edit")
    public String edit(Shipping shipping){
        log.info("保存委托单");
        //根据委托单id找到装箱单
        Packing packing = packingService.findById(shipping.getShippingOrderId());
        //设置创建人
        shipping.setCreateBy(getLoginUser().getId());
        //设置创建部门
        shipping.setCreateDept(getLoginUser().getDeptId());
        //设置创建日期
        shipping.setCreateTime(new Date());
        //设置当前公司id
        shipping.setCompanyId(getLoginCompanyId());
        //设置当前公司名称
        shipping.setCompanyName(getLoginCompanyName());
        //修改委托单保存之后的状态
        shipping.setState(0);
        //保存
        shippingService.save(shipping);
        //设置装箱单生成委托单之后的状态
        packing.setState(1L);
        //更新装箱单
        packingService.update(packing);
        return "redirect:/cargo/shipping/list.do";
    }

    /**删除委托单
     * /cargo/shipping/delete.do?id=" + id
     * @param id
     * @return redirect:/cargo/shipping/list.do
     */
    @RequestMapping("delete")
    public String delete(String id){
        log.info("删除委托单");
        shippingService.delete(id);
        return "redirect:/cargo/shipping/list.do";
    }
    /**
     * 生成Excel
     * cargo/shipping/downloadExcel.do?id=" + id
     * @param id
     */
    @RequestMapping("downloadExcel")
    public void downloadExcel(String id){
        log.info("生成Excel");
        try {
            //根据id查找装箱单
            Packing packing = packingService.findById(id);
            //根据id查找委托单
            Shipping shipping = shippingService.findById(id);
            //获取Excel模板，文件流
            String path = request.getSession().getServletContext().getRealPath("/template/entrustTemplate.xlsx");
            //导出第一行
            Workbook workbook = new XSSFWorkbook(new FileInputStream(path));
            //获取工作表
            Sheet sheet = workbook.getSheetAt(0);

            Row row = sheet.getRow(3);// 第4行1列
            Cell cell = row.getCell(0);
            cell.setCellValue(shipping.getShipper());
            cell = row.getCell(5);
            cell.setCellValue(getLoginCompanyName());

            row = sheet.getRow(8);// 第9行1列
            cell = row.getCell(0);
            cell.setCellValue(shipping.getConsignee());

            row = sheet.getRow(15);// 第16行1列
            cell = row.getCell(0);
            cell.setCellValue(shipping.getNotifyParty());

            row = sheet.getRow(19);// 第20行1列
            cell = row.getCell(0);
            cell.setCellValue(UUID.randomUUID().toString());
            cell = row.getCell(3);//  第20行4列
            cell.setCellValue(new SimpleDateFormat("MMMM dd,yyyy", Locale.ENGLISH).format(shipping.getLoadingDate()));
            cell = row.getCell(6);//  第20行7列
            cell.setCellValue(shipping.getLcNo());

            row = sheet.getRow(23);// 第24行1列
            cell = row.getCell(0);
            cell.setCellValue(shipping.getPortOfLoading());
            cell = row.getCell(3);// 第24行4列
            cell.setCellValue(shipping.getPortOfTrans());
            cell = row.getCell(6);// 第24行7列
            cell.setCellValue(shipping.getPortOfDischar());

            row = sheet.getRow(29);// 第30行
            row.getCell(0).setCellValue(packing.getMarks());// 第30行1列
            row.getCell(5).setCellValue(packing.getTotalVolum());// 第30行6列
            row.getCell(6).setCellValue(packing.getNetWeights());// 第30行7列
            row.getCell(8).setCellValue(packing.getPackingMoney());// 第30行9列

            row = sheet.getRow(34);// 第35行1列
            row.getCell(1).setCellValue(shipping.getSpecialConditio());

            // 第四：导出下载
            response.setCharacterEncoding("UTF-8");
            // 设置下载响应头（浏览器会以下载方式处理响应结果）
            response.setHeader("content-disposition","attachment;filename=shipping.xlsx");
            ServletOutputStream out = response.getOutputStream();
            // 把excel文件流，写入到response输出流，实现下载
            workbook.write(out);
            workbook.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
